<!--
*@Author: QWP
*@Description: 车辆续保登记
*@Params: pType  1  录入页面       2 保险分析页面
*@Date 2024-09-18 11:11
-->
<template>
  <a-layout
    class="f-h-100 s-bg-white"
    id="test">
    <u-table-header>
      <u-form
        :model="state.searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <a-space>
            <u-icon-button
              itype="search"
              @click="getSearch(1)"
              native-type="submit">
              查询
            </u-icon-button>
            <u-icon-button
              itype="export"
              @click="exportBtn"
              v-if="route.params.pType == 1">
              导出
            </u-icon-button>
          </a-space>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <a-space v-if="route.params.pType == 1">
              <u-icon-button
                itype="add"
                @click="toEdit">
                新增
              </u-icon-button>
              <u-icon-button
                itype="edit"
                @click="toEdit(2)">
                修改
              </u-icon-button>
              <u-icon-button
                @click="deleteBtn"
                itype="delete"
                type="danger">
                删除
              </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="state.columns"
        :data="state.tabData"
        :loading="loading"
        v-model:pagination="pagenation"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => state.tabSelData.splice(0, state.tabSelData.length, ...selectedRows)"
        @onDblclick="
          (record) => {
            state.keyid = record.keyid;
            state.showEdit = true;
          }
        "
        @change="getSearch" />
    </u-table-content>
  </a-layout>

  <!-- 修改 -->
  <Edit
    v-model:open="state.showEdit"
    :title="route.params.pType == 1 ? '保险编辑' : '保险信息'"
    :keyid="state.keyid"
    wrap-class-name="full-modal"
    @success="(state.keyid = ''), (state.showEdit = false), getSearch()"
    @close="state.keyid = ''" />

</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch, onActivated } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router";
import { useBaseStore, useLoginStore } from "@/store";
import { storeToRefs } from "pinia";
import Edit from "./Edit.vue";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import * as insureApi from "@/service/administration/carInsure";
import { formatAmt } from "@/util/format.ts";
import { alertC, confirmC, nullC, numberC, isValue, jsonCopy, messageC } from "@/util/common";
import dayjs from "dayjs";
import { useTableScroll } from "@/hooks/useTable";
import { formatEmergency } from "@/views/oa/officialDoc/dispatch/emergencyTool.ts";

const route = useRoute();
const { loginInfo } = storeToRefs(useLoginStore());
const { VEHICLE_MODEL, VEHICLE_TYPE, ISPROXY, IS_REIMBURSE } = storeToRefs(useBaseStore());

onMounted(() => {
  initPageParams();
});

onActivated(() => {
  initPageParams();
});

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: (total) => `共 ${total} 条`,
});
const formItemProps: FormItemProps = {
  labelWidth: "60px",
  wrapperCol: { span: 24 },
};
const searchEl: Array<_IFormEl> = reactive([
  {
    label: "距保险到期天数",
    key: "dqDays",
    element: "input",
    hide: route.params.pType != 2,
    formItemProps: {
      labelWidth: "110px",
      style: { width: "240px" },
    },
    componentProps: {
      addonAfter: "天",
      placeholder: "保险到期日",
    },
  },
  {
    label: "关键字",
    key: "keywords",
    element: "input",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: { placeholder: "车牌号、部门" },
  },
]);

const loading = ref<boolean>(false);

const state = reactive({
  searchF: {
    model: {
      keywords: null,
      pageType: computed(() => route.params.pType),
    },
    current: 1,
    size: 20,
  },

  total: 0,
  tabData: [],
  tabSelData: [],
  columns: [
    { type: "index", align: "center", title: "序号", width: 50, customRender: ({ index }) => (index += 1) },
    { title: "车牌号", width: 120, dataIndex: "vehiclenumber", align: "center" },
    {
      title: "车型",
      width: 120,
      dataIndex: "vehiclemodel_echo",
      align: "center",
      customRender: ({ text }) => {
        let info = VEHICLE_MODEL.value.find((i) => i.keyid == text) || {};
        return info["label"];
      },
    },
    {
      title: "排量",
      width: 120,
      dataIndex: "exhaustvolume",
      align: "center",
      customRender: ({ text, record }) => {
        if (text) {
          return `${text} L`;
        } else if (record.turbocharging) {
          return `${record.turbocharging} T`;
        }
      },
    },
    {
      title: "车辆类型",
      width: 120,
      dataIndex: "vehicletype",
      align: "center",
      customRender: ({ text }) => {
        let info = VEHICLE_TYPE.value.find((i) => i.id == text) || {};
        return info["label"];
      },
    },
    { title: "所属部门", width: 120, dataIndex: "ssdeptname", align: "center" },
    ...(route.params.pType == 1 ? [{ title: "是否代管", width: 120, dataIndex: "isproxy", align: "center" }] : []),
    { title: "保险公司", width: 160, dataIndex: "mechanismname", align: "center" },
    {
      title: "保费(元)",
      width: 120,
      dataIndex: "insuramt",
      align: "center",
      customRender: ({ text }) => {
        return formatAmt(text);
      },
    },
    {
      title: "保险生效日",
      width: 160,
      dataIndex: "insureffectdate",
      align: "center",
      customRender: ({ text }) => {
        return (text || "").split(" ")[0];
      },
    },
    {
      title: "购买时间",
      width: 160,
      dataIndex: "insurancedate",
      align: "center",
      customRender: ({ text }) => {
        return (text || "").split(" ")[0];
      },
    },
    ...(route.params.pType == 2
      ? [
          // { title: '是否出保', width: 100, dataIndex: 'isinsure', align: 'center' ,},
          {
            title: "距保险到期天数",
            width: 140,
            dataIndex: "insurancedate",
            align: "center",
            customRender: ({ text, record }) => {
              return nextToNowDays(record.insureffectdate);
            },
          },
        ]
      : []),
  ],

  showEdit: false,
  isCheck: false,
  keyid: "",

  cxdata: VEHICLE_MODEL.value,
  cllxdata: VEHICLE_TYPE.value,
  isdgdata: ISPROXY.value,
  isbxdata: IS_REIMBURSE.value,
});

// 列表查询
async function getSearch(current?: number) {
  if (current == 1) {
    pagenation.current = current;
  }

  state.searchF.size = pagenation.pageSize;
  state.searchF.current = pagenation.current;

  loading.value = true;
  try {
    const res = await insureApi.search(state.searchF);
    if (res.code == 0) {
      state.tabData = res.data.records;
      pagenation.total = numberC(res.data.total);
    }
  } catch (error) {}
  loading.value = false;
}

// 初始化
function initPageParams() {
  if (route.params.pType == 2) {
    state.searchF.model.dqDays = 30;
  } else {
    delete state.searchF.model.dqDays;
  }
  if (state.tabData.length == 0) {
    getSearch();
  }
}

// 新增、修改
function toEdit(type?: number) {
  state.keyid = "";
  if (type == 2) {
    if (state.tabSelData.length !== 1) {
      messageC("能且只能选择一条数据进行编辑!");
      return;
    }
    state.keyid = state.tabSelData[0].keyid;
  }

  state.showEdit = true;
}

// 删除
async function deleteBtn() {
  if (state.tabSelData.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }
  let ids = state.tabSelData.map((item) => item.keyid);
  await alertC("确定删除该条数据?", "confirm");
  loading.value = true;
  try {
    const res = await insureApi.del({ ids: ids.join(",") });
    if (res.code == 0) {
      messageC(res.msg, "success");
      getSearch();
    } else {
      messageC(res.msg, "error");
    }
  } catch (e) {}
  loading.value = false;
}

// 计算下一次购买日局现在的天数
function nextToNowDays(nextDate: any) {
  if (nextDate) {
    let deadDay = dayjs(nextDate).add(1, "year").subtract(1, "day").diff(dayjs(), "day") + 1;
    let deadDay1 = deadDay < 0 ? `已到期${Math.abs(deadDay)}` : deadDay;
    return deadDay <= 30 ? formatEmergency(4, `${deadDay1}天`) : `${deadDay1}天`;
  }
}

// 导出
async function exportBtn() {
  loading.value = true;
  try {
    const res = await insureApi.download({ ...state.searchF, size: -1, filename: "车辆保险信息" });
  } catch (error) {}
  loading.value = false;
}
</script>
<style lang="scss"></style>
